﻿using System;
using System.IO;
using System.Net;
using System.Linq;

namespace IOFtp
{
    public class FtpFile : FtpFileSystemObject
    {
        public string FilePath { get; private set; }
        //  public long Length { get; internal set; }
        public FtpDirectory ParentDirectory { get; private set; }

        public FtpFile( Uri requestUri, NetworkCredential credentials )
            : base( requestUri, credentials )
        {
            FileInfo fi = new FileInfo( requestUri.AbsolutePath );
            if( fi.Name == String.Empty && fi.Extension == String.Empty )
                throw new Exception( "Specified path is not a file" );

            this.FilePath = requestUri.AbsoluteUri;

            var parentDir = Path.GetDirectoryName( this.CurrentDirectory.ToString() ).Replace( @"\", @"/" ).Replace( "ftp:/", "ftp://" );
            this.ParentDirectory = new FtpDirectory( parentDir, credentials );
        }

        public FtpFile( string requestUri, NetworkCredential credentials )
            : this( new Uri( requestUri ), credentials ) { }

        public override void Download( string destination )
        {
            string localPath = Path.Combine( destination, this.Name );
            this.WebClient.DownloadFile( this.FullPath, localPath );
        }

        public override void Delete()
        {
            this.Request = (FtpWebRequest)WebRequest.Create( this.FullPath );
            this.Request.Credentials = this.Credentials;
            this.Request.Method = WebRequestMethods.Ftp.DeleteFile;

            FtpWebResponse response = (FtpWebResponse)this.Request.GetResponse();
        }
    }
}